package com.woniu.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.exception.LXLGException;
import com.woniu.user.common.VIPException;
import com.woniu.user.common.config.AlipayConfigq;
import com.woniu.user.infra.model.UserVipRelation;
import com.woniu.user.infra.model.Vip;
import com.woniu.user.infra.mapper.VipMapper;
import com.woniu.user.service.UserVipRelationService;
import com.woniu.user.service.VipService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.service.dto.VipDto;
import com.woniu.util.DateUtil;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-11-26
 */
@Service
public class VipServiceImpl extends ServiceImpl<VipMapper, Vip> implements VipService {

    @Resource
    private UserVipRelationService userVipRelationService;
    @Resource
    private  RocketMQTemplate rmt;

    /**
     * 查看所有会员卡
     *
     * @return
     */
    @Override
    public List<VipDto> vipCardInfo() {
        QueryWrapper<Vip> qw = new QueryWrapper<>();
        qw.eq("state", "NORMAL");
        List<Vip> vipCardInfos = list(qw);
        List<VipDto> vipDtos = BeanUtil.copyToList(vipCardInfos, VipDto.class);
        return vipDtos;
    }

    /**
     * 购买会员卡
     *
     * @param cardId
     * @return
     */
    @Override
    public String buyCard(Integer cardId,Integer userId) {
        Vip vipCardInfo = getOne(new QueryWrapper<Vip>().eq("vip_id", cardId));
        if (vipCardInfo == null) throw new LXLGException(VIPException.VIP_NOT_EXIST);
        if (!vipCardInfo.getState().equals("NORMAL")) throw new LXLGException(VIPException.VIPCARD_STATE_EXCEPTION);
        //查看用户是否有会员卡

        UserVipRelation userCardInfo = userVipRelationService.getOne(new QueryWrapper<UserVipRelation>().eq("card_id", cardId).eq("user_id", userId));
        if (userCardInfo != null) throw new LXLGException(VIPException.VIPCARD_EXSIT);
        //查看用户所有的VIP卡
        List<UserVipRelation> cardInfos = userVipRelationService.list(new QueryWrapper<UserVipRelation>().eq("user_id", userId).orderByAsc("discount"));
        if (cardInfos.size()>0){
            //取最高等级的vip卡，不可以购买等级低于最高等级的vip卡
            UserVipRelation userVipRelation = cardInfos.get(0);
            if (vipCardInfo.getDiscount().compareTo(userVipRelation.getDiscount())>0)throw new LXLGException(VIPException.VIP_EXSIT_HIGHER);

        }

        UserVipRelation uvr = new UserVipRelation();
        uvr.setCardId(cardId);
        uvr.setUserId(userId);

        uvr.setCardNum("lxlg" + IdUtil.getSnowflake(1, 1).nextIdStr());
        uvr.setStartTime(DateUtil.parseDateLong());

        //创建Calendar实例
        Calendar cal = Calendar.getInstance();
        //获取当前时间
        cal.setTime(new Date());
        //在当前时间加上一年
        cal.add(Calendar.YEAR, 1);
        //格式化转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(cal.getTime());
        System.out.println(format);

        uvr.setEndTime(format1);
        uvr.setStatus("UNPAID");
        uvr.setBuyTime(DateUtil.parseDateLong());
        uvr.setBuyMoney(vipCardInfo.getCardAmount());
        uvr.setDiscount(vipCardInfo.getDiscount());
        userVipRelationService.save(uvr);

        Message<Integer> message = MessageBuilder.withPayload(uvr.getId()).build();
        rmt.syncSend("lxlg-vip-order",message,2000,8);

        return uvr.getCardNum();
    }

    @Override
    public String payVipCard(String cardNum) throws UnsupportedEncodingException, AlipayApiException {
        //查询订单状态
        UserVipRelation cardInfo = userVipRelationService.getOne(new QueryWrapper<UserVipRelation>().eq("card_num", cardNum));
        if (cardInfo != null && cardInfo.getStatus().equals("UNPAID")) {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigq.gatewayUrl, AlipayConfigq.app_id, AlipayConfigq.merchant_private_key, "json", AlipayConfigq.charset, AlipayConfigq.alipay_public_key, AlipayConfigq.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfigq.return_url);
            alipayRequest.setNotifyUrl(AlipayConfigq.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(cardNum.getBytes("ISO-8859-1"), "UTF-8");
            //付款金额，必填
            String total_amount = new String(cardInfo.getBuyMoney().toString().getBytes("ISO-8859-1"), "UTF-8");
            //订单名称，必填
            String subject = "支付会员卡";
            //商品描述，可空
            String body = "会员卡";

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(result);
            return result;
        }
        return null;
    }

}
